// 请求拦截器
const Request = require("./request");
const Api = new Request();
import store from "@/store";
import Vue from "vue"
// 请求拦截器
Api.interceptors.request((request) => {

    const token = uni.getStorageSync("token") || "";
    // 加载处理
    if (request.loading) {
        uni.showLoading({
            title: "请稍等...",
            mask: false,
        });
    }
    // 请求头处理
    // if (token) request.header["Authorization"] = token;

    if (request.params) {
        request.header['Content-Type'] = 'application/x-www-form-urlencoded'
        request.data = request.params
        delete request.params
    } else {
        request.header['Content-Type'] = 'application/json'
    }

    // 空值处理
    for (let i in request.data) {
        if (!request.data[i] && request.data[i] !== 0) {
            delete request.data[i];
        }
    }
    return request;
});

// 响应拦截器
Api.interceptors.response(async (response, options) => {
    // console.log('参数', options);
    // console.log('响应', response);
    console.log(options.apiName, {
        请求参数: {...options.data},
        响应参数: {
            code: response.data.code,
            data: response.data.data,
        },
    });

    uni.hideLoading();
    const staticCode = response.data.code;
    // 响应头处理，刷新token
    if (response.header.Authorization) uni.setStorageSync("token", response.header.Authorization);

    switch (staticCode) {
        case 200:
            return response.data;
        case 400:
            uni.showToast({
                title: response.data.msg,
                icon: "none",
                duration: 2000,
            });
            return new Object(response.data);
        default:
            console.log(`[${options.apiName}接口错误]`, {
                code: response.statusCode,
                data: response.data,
            });
            uni.showToast({
                title: response.data.message || `[${options.apiName}接口错误]`,
                icon: "none",
            });

            return response.data;
    }
});

module.exports = Api;
